//
//  CircleOfPetViewController.m
//  LoveOfPet
//
//  Created by dllo on 15/11/11.
//  Copyright © 2015年 孔维. All rights reserved.
//

#import "CircleOfPetViewController.h"
#import "CircleOfPetCollectionViewCell.h"
#import "CameraCollectionViewCell.h"
#import "CircleOfPetCollectionReusableView.h"
#import "PhotographerViewController.h"
#import "LuBDefine.h"
#import "AlbumViewController.h"
#import "DetailOfCircleViewController.h"
#import "Recommend.h"
#import "Camera.h"
#import "LBAFNetworking.h"

@interface CircleOfPetViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, retain)UICollectionView *collectionView;

@property (nonatomic, retain)NSMutableArray *recommendArray;

@property (nonatomic, retain)NSMutableArray *cameraArray;

@end

@implementation CircleOfPetViewController

- (void)dealloc{
    [_collectionView release];
    [_recommendArray release];
    [_cameraArray release];
    [super dealloc];
}

//初始化
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.recommendArray = [NSMutableArray array];
        self.cameraArray = [NSMutableArray array];
    }
    return self;
}

//加载
- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.translucent = NO;

    [self createCircleOfPetViewController];
    [self downloadSquare];
    [self downloadDataStar];
    // Do any additional setup after loading the view.
}

//解析数据
- (void)downloadSquare{
    NSString *url = @"http://api.epetbar.com/gutouv2/channel.html?do=square&develop=0&ver=2.85&os=ios";
    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    NSString *recommendPath = [path stringByAppendingPathComponent:@"commend.plist"];
    NSMutableArray *tempArray = [NSKeyedUnarchiver unarchiveObjectWithFile:recommendPath];
    if (tempArray) {
        for (NSDictionary *dic in tempArray) {
            Recommend *recommend = [Recommend recommendWithDictionary:dic];
            [self.recommendArray addObject:recommend];
        }
        [self.collectionView reloadData];
    }else{
    [LBNetWork handleGETWithUrlString:url parameters:nil showHuD:NO onView:self.view successfulBlock:^(id responseObject) {
        //第一分区数组
        NSArray *recommendArray = [NSArray arrayWithArray:[[responseObject objectForKey:@"data"] objectForKey:@"recomm"]];
        
        [NSKeyedArchiver archiveRootObject:recommendArray toFile:recommendPath];
        //第一分区数据
        for (NSDictionary *dic in recommendArray) {
            Recommend *recommend = [Recommend recommendWithDictionary:dic];
            [self.recommendArray addObject:recommend];
        }
        [self.collectionView reloadData];
    } failureBlock:^(NSError *error) {
        NSLog(@"失败1");
    }];
    }
}

//解析数据
- (void)downloadDataStar{
    NSString *url = @"http://api.epetbar.com/gutouv2/star.html?limit=10&do=home&page=1";
    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    NSString *starPath = [path stringByAppendingPathComponent:@"star.plist"];
    NSMutableArray *tempArray = [NSKeyedUnarchiver unarchiveObjectWithFile:starPath];
    if (tempArray) {
        for (NSDictionary *dic in tempArray) {
            Camera *camera = [Camera cameraWithDictionary:dic];
            [self.cameraArray addObject:camera];
        }
        [self.collectionView reloadData];
    }else{
        [LBNetWork handleGETWithUrlString:url parameters:nil showHuD:YES onView:self.view successfulBlock:^(id responseObject) {
            NSArray *cameraArray =[NSArray arrayWithArray:[[responseObject objectForKey:@"data"] objectForKey:@"camera"]];
            
            [NSKeyedArchiver archiveRootObject:cameraArray toFile:starPath];
            
            for (NSDictionary *dic in cameraArray) {
                Camera *camera = [Camera cameraWithDictionary:dic];
                [self.cameraArray addObject:camera];
            }
            [self.collectionView reloadData];
        } failureBlock:^(NSError *error) {
            NSLog(@"失败2");
        }];
    }
}

//创建视图
- (void)createCircleOfPetViewController{
    self.title = @"宠物圈";
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
//    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//    button.frame = CGRectMake(0, 0, 44, 44);
//    [button setTitle:@"" forState:UIControlStateNormal];
//    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [button addTarget:self action:@selector(returnToNext:) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];


    UICollectionViewFlowLayout *collectionViewlayout = [[UICollectionViewFlowLayout alloc]init];
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, CWIDTH, CHEIGHT - 64 - 49) collectionViewLayout:collectionViewlayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
    [self.view addSubview:self.collectionView];
    [collectionViewlayout release];
    [_collectionView release];
    
    //注册
    [self.collectionView registerClass:[CircleOfPetCollectionViewCell class] forCellWithReuseIdentifier:@"CircleOfPetCollectionViewCell"];
    
    [self.collectionView registerClass:[CameraCollectionViewCell class] forCellWithReuseIdentifier:@"CameraCollectionViewCell"];
    
    [self.collectionView registerClass:[CircleOfPetCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CircleOfPetCollectionReusableView"];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionReusableView"];
}

//返回分区数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 2;
}

//每个区的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return self.recommendArray.count;
    }else{
        return self.cameraArray.count;
    }
}
//- (void)returnToNext:(UIButton *)button{
//    
//}

//返回边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(3, 3, 3, 3);
}

//cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //第一分区
    if (indexPath.section == 0) {
        if (indexPath.row == 0 || indexPath.row == 1) {
            return CGSizeMake(CWIDTH / 2 - 6, CWIDTH /  2 - 6);
        }if (indexPath.row == 2 || indexPath.row == 3 || indexPath.row == 4) {
            return CGSizeMake(CWIDTH / 3 - 6, CWIDTH / 3 - 6);
        }else{
            return CGSizeMake(CWIDTH / 4 - 6, CWIDTH / 4 - 6);
        }
    }
    //第二分区
    else{
        if (indexPath.row == 0) {
            return CGSizeMake(CWIDTH - 6, CHEIGHT / 1.5);
        }
        if (indexPath.row == 1 || indexPath.row == 2){
            return CGSizeMake(CWIDTH / 2 - 6, CWIDTH / 3 - 6);
        }
        else{
            return CGSizeMake(CWIDTH - 6, CWIDTH / 2 - 6);
        }
    }
}

//返回行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 5;
}

//返回列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 5;
}

//实现CELL
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        CircleOfPetCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CircleOfPetCollectionViewCell" forIndexPath:indexPath];
        
        CATransition *anim = [CATransition animation];
        anim.type = @"rippleEffect"; // 动画过渡类型
        anim.subtype = kCATransitionFromTop; // 动画过渡方向
        anim.duration = 1; // 动画持续1s
        // 代理，动画执行完毕后会调用delegate的animationDidStop:finished:
        anim.delegate = self;
        [cell.layer addAnimation:anim forKey:@"key"];

        cell.recommend = self.recommendArray[indexPath.row];
        return cell;
    }else{
        CameraCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CameraCollectionViewCell" forIndexPath:indexPath];
        
        CATransition *anim = [CATransition animation];
        anim.type = @"rippleEffect"; // 动画过渡类型
        anim.subtype = kCATransitionFromTop; // 动画过渡方向
        anim.duration = 1; // 动画持续1s
        // 代理，动画执行完毕后会调用delegate的animationDidStop:finished: ,这里没写
//        anim.delegate = self;
        [cell.layer addAnimation:anim forKey:@"key"];
        
        cell.camera = self.cameraArray[indexPath.row];
        return cell;
    }
}

//头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader) {
        if (indexPath.section == 0) {
            UICollectionReusableView *resuableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionReusableView" forIndexPath:indexPath];
            UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 150, 30)];
            title.backgroundColor = [UIColor whiteColor];
            title.text = @"  宠物广场";
            title.font = [UIFont systemFontOfSize: 15];
            title.textColor = [UIColor grayColor];
            [resuableView addSubview:title];
            [title release];
            return resuableView;
        }else{
            CircleOfPetCollectionReusableView *resuableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CircleOfPetCollectionReusableView" forIndexPath:indexPath];
            resuableView.titleLabel.text = @"宠物摄影";
            [resuableView.detailBtn addTarget:self action:@selector(detailBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            return resuableView;
        }
    }else{
        return 0;
    }
}

- (void)detailBtnAction:(UIButton *)btn{
    PhotographerViewController *photographerViewController = [[PhotographerViewController alloc]init];
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:photographerViewController animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    [photographerViewController release];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
        return CGSizeMake(CWIDTH, 40);
}

//点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        DetailOfCircleViewController *detailOfCircleViewController = [[DetailOfCircleViewController alloc]init];
        detailOfCircleViewController.recommend = self.recommendArray[indexPath.row];
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detailOfCircleViewController animated:YES];
        self.hidesBottomBarWhenPushed = NO;
        [detailOfCircleViewController release];
    }else {
        AlbumViewController *albumViewController = [[AlbumViewController alloc]init];
        albumViewController.ppid = [self.cameraArray[indexPath.row] ppid];
        albumViewController.photo_des = [self.cameraArray[indexPath.row] title];
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:albumViewController animated:YES];
        self.hidesBottomBarWhenPushed = NO;
        [albumViewController release];
    }
}

- (void)viewWillAppear:(BOOL)animated{
    self.hidesBottomBarWhenPushed = NO;
    self.navigationController.navigationBar.translucent = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
